var area_jsonFilePath = 'js/area.json';

angular
    .module('Area', [])
    .service('getArea', ['$http', '$q', function($http, $q) {
        var self = this;

        self.get = function() {
            var storage = window.localStorage;
            //取本地缓存
            var storageArea = JSON.parse(storage['my_def_area'] || '{}');
            //如果本地缓存已经过期，清空，过期时间为20天
            if (storageArea && storageArea.lastTime && ((new Date().getTime() - storageArea.lastTime) / 1000.0 / 60.0 / 60.0 / 24.0) >= 20) {
                storage.removeItem('my_def_area');
            }
            self.area = self.area || storageArea || {};

            var deferred = $q.defer();
            var promise = deferred.promise;
            if (self.area.area) {
                deferred.resolve(self.area);
            } else {
                $http.get(area_jsonFilePath)
                    .success(function(res) {
                        storage['my_def_area'] = JSON.stringify(angular.extend(res, { lastTime: new Date().getTime() }));
                        self.area = res;
                        deferred.resolve(res);
                    })
                    .error(function(res) {
                        deferred.resolve(null);
                    });
            }
            return promise;
        };
    }])
    .directive('ngArea', ['getArea', '$timeout', function(getArea, $timeout) {
        return {
            controller: function($scope) {
                if (!$scope.required) $scope.required = false;

                getArea.get()
                    .then(function(area) {
                        $scope.my_def_area = area.area;
                        $timeout(function() {
                            $scope.changePro();
                            $scope.changeCity();
                        }, 300);
                    });

                $scope.changePro = function() {
                    if (!$scope.province || !$scope.my_def_area) {
                        $scope.cityList = [];
                    } else {
                        for (var i = 0; i < $scope.my_def_area.province.length; i++) {
                            if ($scope.my_def_area.province[i].name == $scope.province) {
                                var city = $scope.my_def_area.province[i].city;
                                if (angular.isArray(city)) {
                                    $scope.cityList = city;
                                } else {
                                    $scope.cityList = [city];
                                }
                                break;
                            }
                        }
                    }
                };

                $scope.changeCity = function() {
                    if (!$scope.city || !$scope.my_def_area) {
                        $scope.countyList = [];
                    } else {
                        for (var i = 0; i < $scope.cityList.length; i++) {
                            if ($scope.cityList[i].name == $scope.city) {
                                var county = $scope.cityList[i].county;
                                if (angular.isArray(county)) {
                                    $scope.countyList = county;
                                } else {
                                    $scope.countyList = [county];
                                }
                                break;
                            }
                        }
                    }
                };
                $scope.$watch('city', function(newValue, oldValue) {
                    $scope.changeCity();
                });
                $scope.$watch('province', function(newValue, oldValue) {
                    $scope.changePro();
                });

            },
            link: function($scope, $elem, $attrs) {
                if ($scope.hasCity === 'false' || $scope.hasCounty === 'false')
                    $elem[0].removeChild($elem[0].children[2]);
                if ($scope.hasCity === 'false')
                    $elem[0].removeChild($elem[0].children[1]);
                // if ($scope.cssTheme !== 'bootstrap') {
                //     for (var i = 0; i < $elem[0].children.length; i++) {
                //         $elem[0].children[i].setAttribute('style', 'display:inline-block; padding:0 10px;');
                //     }
                // }
            },
            restrict: 'AE',
            scope: {
                province: '=',
                city: '=',
                county: '=',
                divClass: '@',
                selClass: '@',
                hasCity: '@',
                hasCounty: '@',
                required: '@'
            },
            template: '<div ng-class="divClass" ><select ng-model="province" ng-options="pro.name as pro.name for pro in my_def_area.province" ng-class="selClass" ng-required="{{required}}" ><option value="">请选择省份</option></select></div>' +
                '<div ng-class="divClass" ><select ng-model="city" ng-options="cty.name as cty.name for cty in cityList" ng-class="selClass" ng-required="{{required}}"><option value="">请选择城市</option></select></div>' +
                '<div ng-class="divClass" ><select ng-model="county" ng-options="county.name as county.name for county in countyList" ng-class="selClass" ng-required="{{required}}"><option value="">请选择区县</option></select></div>'
        }
    }]);